<template>
  <div class="exam-manage-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Edit /></el-icon>
          <div class="header-text">
            <h2>考试管理</h2>
            <p>创建和管理考试试卷</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="$router.push('/learning/question-bank')">
            <el-icon><Collection /></el-icon>
            题库管理
          </el-button>
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            创建试卷
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 试卷列表 -->
    <el-card shadow="never">
      <el-table :data="tableData" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="试卷名称" min-width="200" />
        <el-table-column prop="courseName" label="关联课程" width="180" />
        <el-table-column prop="type" label="考试类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)" size="small">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="questionCount" label="题目数" width="100" />
        <el-table-column prop="totalScore" label="总分" width="80" />
        <el-table-column prop="duration" label="时长" width="100" />
        <el-table-column label="考试时间" width="280">
          <template #default="{ row }">
            {{ row.startTime }} ~ {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleManageQuestions(row)">
              <el-icon><Document /></el-icon>
              题目
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑试卷对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="700px"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="试卷名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
                <el-option label="课后测验" value="quiz" />
                <el-option label="期末考试" value="exam" />
                <el-option label="能力评估" value="assessment" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" style="width: 100%">
                <el-option label="Vue 3 从入门到精通" value="1" />
                <el-option label="产品思维与方法论" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number v-model="form.totalScore" :min="1" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="及格分" prop="passScore">
              <el-input-number v-model="form.passScore" :min="1" :max="form.totalScore" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试时长" prop="duration">
              <el-input-number v-model="form.durationMinutes" :min="10" :max="300" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="考试说明">
          <el-input v-model="form.instruction" type="textarea" :rows="4" placeholder="请输入考试说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>

    <!-- 题目管理对话框 -->
    <el-dialog v-model="showQuestionDialog" title="题目管理" width="900px">
      <div class="question-manage">
        <el-button type="primary" @click="showAddQuestionDialog = true" style="margin-bottom: 16px;">
          <el-icon><Plus /></el-icon>
          从题库添加
        </el-button>

        <el-table :data="currentExamQuestions">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="content" label="题目内容" min-width="300" />
          <el-table-column prop="type" label="题型" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getQuestionTypeName(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分值" width="80" />
          <el-table-column prop="difficulty" label="难度" width="100">
            <template #default="{ row }">
              <el-tag :type="getDifficultyType(row.difficulty)" size="small">
                {{ row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ $index }">
              <el-button link type="danger" size="small" @click="handleRemoveQuestion($index)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-empty v-if="currentExamQuestions.length === 0" description="还没有题目，从题库添加吧" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit, Plus, Search, Refresh, Document, Delete, Collection
} from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([
  {
    id: 1,
    title: 'Vue 3 基础知识测验',
    courseName: 'Vue 3 从入门到精通',
    type: 'quiz',
    questionCount: 20,
    totalScore: 100,
    passScore: 60,
    duration: '60分钟',
    startTime: '2024-01-15 09:00',
    endTime: '2024-01-20 18:00',
    status: 'published'
  },
  {
    id: 2,
    title: 'Composition API 考试',
    courseName: 'Vue 3 从入门到精通',
    type: 'exam',
    questionCount: 30,
    totalScore: 100,
    passScore: 70,
    duration: '90分钟',
    startTime: '2024-01-10 09:00',
    endTime: '2024-01-15 18:00',
    status: 'draft'
  }
])

// 对话框
const showDialog = ref(false)
const showQuestionDialog = ref(false)
const showAddQuestionDialog = ref(false)
const formRef = ref(null)
const currentRow = ref(null)
const currentExamQuestions = ref([])

const dialogTitle = computed(() => currentRow.value ? '编辑试卷' : '创建试卷')

// 表单
const form = reactive({
  title: '',
  type: '',
  courseId: '',
  totalScore: 100,
  passScore: 60,
  durationMinutes: 60,
  startTime: null,
  endTime: null,
  instruction: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择考试类型', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择关联课程', trigger: 'change' }]
}

// 方法
const handleEdit = (row) => {
  currentRow.value = row
  Object.assign(form, {
    title: row.title,
    type: row.type,
    courseId: '1',
    totalScore: row.totalScore,
    passScore: row.passScore,
    durationMinutes: parseInt(row.duration),
    startTime: row.startTime,
    endTime: row.endTime,
    instruction: '考试说明...'
  })
  showDialog.value = true
}

const handleManageQuestions = (row) => {
  currentRow.value = row
  // 模拟加载题目
  currentExamQuestions.value = [
    {
      id: 1,
      content: 'Vue 3 的 Composition API 中，ref 和 reactive 的区别是什么？',
      type: 'single',
      score: 5,
      difficulty: '中等'
    },
    {
      id: 2,
      content: '请简述 Vue 3 的响应式原理。',
      type: 'essay',
      score: 10,
      difficulty: '困难'
    }
  ]
  showQuestionDialog.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该试卷吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      showDialog.value = false
    }
  })
}

const handleRemoveQuestion = (index) => {
  currentExamQuestions.value.splice(index, 1)
  ElMessage.success('移除成功')
}

const getTypeName = (type) => {
  const map = {
    quiz: '课后测验',
    exam: '期末考试',
    assessment: '能力评估'
  }
  return map[type] || type
}

const getTypeTag = (type) => {
  const map = {
    quiz: '',
    exam: 'warning',
    assessment: 'success'
  }
  return map[type] || ''
}

const getStatusName = (status) => {
  const map = {
    published: '已发布',
    draft: '草稿'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    published: 'success',
    draft: 'info'
  }
  return map[status] || ''
}

const getQuestionTypeName = (type) => {
  const map = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    essay: '问答题'
  }
  return map[type] || type
}

const getDifficultyType = (difficulty) => {
  const map = {
    简单: 'success',
    中等: 'warning',
    困难: 'danger'
  }
  return map[difficulty] || ''
}
</script>

<style scoped>
.exam-manage-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.question-manage {
  max-height: 500px;
  overflow-y: auto;
}
</style>

